<template>
  <div>
    <div class="mb8">
      <el-button type="primary" size="mini" @click="handleAddMaterial">
        <i class="el-icon-plus"></i> 添加物料
      </el-button>
    </div>
    
    <el-table :data="displayMaterialList" size="mini" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="物料编码" prop="materialCode" width="120" />
      <el-table-column label="物料名称" prop="materialName" min-width="150" />
      <el-table-column label="器具型号" prop="containerMaterialCode" width="120" />
      <el-table-column label="器具型号名称" prop="containerMaterialName" width="120" />
      <el-table-column label="收容数" prop="capacityCount" width="80" align="center" />
      <el-table-column label="体积(m³)" prop="volume" width="100" align="center" />
      <el-table-column label="重量(kg)" prop="weight" width="100" align="center" />
      <el-table-column label="货值(元)" prop="goodsValue" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.goodsValue ? scope.row.goodsValue.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column label="内衬方案" prop="liningScheme" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleEditMaterial(scope.row, scope.$index)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            style="color: #f56c6c;"
            @click="handleDeleteMaterial(scope.row, scope.$index)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 物料操作日志（编辑模式下显示） -->
    <div v-if="isEdit && materialOperations.length > 0" style="margin-top: 20px;">
      <el-divider content-position="left">操作记录</el-divider>
      <el-timeline size="small">
        <el-timeline-item
          v-for="(op, index) in materialOperations"
          :key="index"
          :type="getOperationType(op.operationType)"
        >
          <div>
            <span class="operation-type">{{ getOperationText(op.operationType) }}</span>
            <span class="material-code">{{ op.materialCode }}</span>
            <span class="material-name">{{ op.materialName }}</span>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>
    
    <!-- 物料编辑对话框 -->
    <el-dialog
      :title="materialDialogTitle"
      :visible.sync="materialDialogVisible"
      width="600px"
      :modal="false"
      :before-close="handleMaterialDialogClose"
    >
      <el-form ref="materialForm" :model="materialForm" :rules="materialRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="materialForm.materialCode" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="materialForm.materialName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="器具型号编码" prop="containerMaterialCode">
              <el-input v-model="materialForm.containerMaterialCode" placeholder="请输入器具型号编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="器具型号名称" prop="containerMaterialName">
              <el-input v-model="materialForm.containerMaterialName" placeholder="请输入器具型号名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收容数" prop="capacityCount">
              <el-input-number 
                v-model="materialForm.capacityCount" 
                :min="1" 
                :max="9999"
                controls-position="right"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货值(元)" prop="goodsValue">
              <el-input-number 
                v-model="materialForm.goodsValue" 
                :min="0" 
                :precision="2"
                :step="1"
                controls-position="right"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="体积(m³)" prop="volume">
              <el-input-number 
                v-model="materialForm.volume" 
                :min="0" 
                :precision="4"
                :step="0.1"
                controls-position="right"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重量(kg)" prop="weight">
              <el-input-number 
                v-model="materialForm.weight" 
                :min="0" 
                :precision="4"
                :step="0.1"
                controls-position="right"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="内衬方案" prop="liningScheme">
          <el-input 
            v-model="materialForm.liningScheme" 
            type="textarea"
            :rows="2"
            placeholder="请输入内衬方案，格式：层板:5;垫块:20;"
          />
          <div class="form-tip">格式说明：内衬类型:数量;内衬类型:数量;</div>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleMaterialDialogClose">取 消</el-button>
        <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "MaterialConfigForm",
  props: {
    materialList: {
      type: Array,
      default: () => []
    },
    materialOperations: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      materialDialogVisible: false,
      materialDialogTitle: '',
      materialForm: {},
      currentMaterialIndex: -1,
      isEditingMaterial: false,
      materialRules: {
        materialCode: [
          { required: true, message: "物料编码不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "物料编码长度在1到50个字符", trigger: "blur" }
        ],
        materialName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" },
          { min: 1, max: 100, message: "物料名称长度在1到100个字符", trigger: "blur" }
        ],
        containerMaterialCode: [
          { required: true, message: "器具型号编码不能为空", trigger: "blur" }
        ],
        containerMaterialName: [
          { required: true, message: "器具型号名称不能为空", trigger: "blur" }
        ],
        capacityCount: [
          { required: true, message: "收容数不能为空", trigger: "blur" },
          { type: 'number', min: 1, message: "收容数必须大于0", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    displayMaterialList() {
      return this.materialList || [];
    }
  },
  watch: {
    materialList: {
      handler(newVal) {
        console.log('MaterialConfigForm - materialList 变化:', newVal);
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 添加物料
    handleAddMaterial() {
      this.resetMaterialForm();
      this.materialDialogTitle = '添加物料';
      this.isEditingMaterial = false;
      this.currentMaterialIndex = -1;
      this.materialDialogVisible = true;
    },
    
    // 编辑物料
    handleEditMaterial(material, index) {
      this.materialForm = { ...material };
      this.materialDialogTitle = '修改物料';
      this.isEditingMaterial = true;
      this.currentMaterialIndex = index;
      this.materialDialogVisible = true;
    },
    
    // 删除物料
    handleDeleteMaterial(material, index) {
      this.$confirm('确认删除该物料配置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.isEdit && material.projectMaterialId) {
          // 编辑模式下，添加删除操作
          this.addMaterialOperation('delete', {
            projectMaterialId: material.projectMaterialId
          });
        }
        
        // 从列表中移除
        this.materialList.splice(index, 1);
        this.$message.success('删除成功');
        this.$emit('delete-material', material);
      });
    },
    
    // 提交物料表单
    submitMaterialForm() {
      this.$refs.materialForm.validate(valid => {
        if (valid) {
          if (this.isEditingMaterial) {
            // 修改物料
            this.$set(this.materialList, this.currentMaterialIndex, { ...this.materialForm });
            
            if (this.isEdit && this.materialForm.projectMaterialId) {
              // 编辑模式下，添加修改操作
              this.addMaterialOperation('update', this.materialForm);
            }
            
            this.$message.success('修改成功');
            this.$emit('edit-material', this.materialForm);
          } else {
            // 新增物料
            const newMaterial = { ...this.materialForm };
            if (!this.materialList) {
              this.$emit('update:materialList', [newMaterial]);
            } else {
              this.materialList.push(newMaterial);
            }
            
            if (this.isEdit) {
              // 编辑模式下，添加新增操作
              this.addMaterialOperation('create', newMaterial);
            }
            
            this.$message.success('添加成功');
            this.$emit('add-material', newMaterial);
          }
          
          this.materialDialogVisible = false;
        }
      });
    },
    
    // 关闭物料对话框
    handleMaterialDialogClose() {
      this.materialDialogVisible = false;
      this.resetMaterialForm();
    },
    
    // 重置物料表单
    resetMaterialForm() {
      this.materialForm = {
        materialCode: '',
        materialName: '',
        containerMaterialCode: '',
        containerMaterialName: '',
        liningScheme: '',
        capacityCount: 1,
        volume: 0,
        weight: 0,
        goodsValue: 0
      };
      if (this.$refs.materialForm) {
        this.$refs.materialForm.resetFields();
      }
    },
    
    // 添加物料操作记录
    addMaterialOperation(operationType, data) {
      if (!this.materialOperations) {
        this.$set(this, 'materialOperations', []);
      }
      
      const operation = {
        operationType,
        ...data
      };
      
      this.materialOperations.push(operation);
    },
    
    // 获取操作类型样式
    getOperationType(type) {
      const typeMap = {
        'create': 'success',
        'update': 'primary',
        'delete': 'danger'
      };
      return typeMap[type] || 'info';
    },
    
    // 获取操作文本
    getOperationText(type) {
      const textMap = {
        'create': '新增',
        'update': '修改',
        'delete': '删除'
      };
      return textMap[type] || '未知';
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.operation-type {
  font-weight: bold;
  margin-right: 8px;
}

.material-code {
  color: #409EFF;
  margin-right: 8px;
}

.material-name {
  color: #666;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style> 